import SparkChannel from '../ipc/sparkchannel'
import path from 'path-browserify'

export const REPORT_TPL_SUFFIX = '.lxs';

export const DATE_FMT = 'YYYY-MM-DD HH:mm:ss';

// 报表类型，0:实时报表，1:日报表，2:周报表，3:月报表，4:年报表
function reportType(id, value, label, timeUnit) {
  return { id, value, label, timeUnit };
}
const REPORT_TYPES = [
  reportType(0, "REAL", "实时报表"),
  reportType(1, "DAY", "日报表", 'day'),
  reportType(2, "WEEK", "周报表", 'week'),
  reportType(3, "MONTH", "月报表", 'month'),
  reportType(4, "YEAR", "年报表", 'year'),
];
const REPORT_TYPE_ID_MAP = {};
const REPORT_TYPE_VALUE_MAP = {};

for (const r of REPORT_TYPES) {
  REPORT_TYPE_ID_MAP[r.id] = r;
  REPORT_TYPE_VALUE_MAP[r.value] = r;
}

export const ReportType = {
  REPORT_TYPES,
  getReportTypeName: (value) => REPORT_TYPE_VALUE_MAP[value].label,
  getReportTypeValue: (id) => REPORT_TYPE_ID_MAP[id].value,
  getByValue: (value) => REPORT_TYPE_VALUE_MAP[value],
  getById: (id) => REPORT_TYPE_ID_MAP[id],
  options: () => {
    return REPORT_TYPES.map(r => {
      return { value: r.id, label: r.label };
    });
  }
}

export const ERROR_CODE = {
  SUCCESS: 0,
  Unknown: 2
}

export const successResp = data => {
  let resp = { "code": ERROR_CODE.SUCCESS, "message": "OK" };
  if (data) {
    resp["data"] = data;
  }
  return resp;
};


const defaultConfig = {
  // 报表类型
  // 实时报表-REAL，日报表-DAY，周报表-WEEK，月报表-MONTH，年报表-YEAR
  // "book_type": "DAY",
  // 空值填充0
  "zero": false,
  // 是否录入制表用户
  "input_username": false,
  // 是否允许自定义时间段
  "custom_time_range": true,

  // 自动生成配置
  // NOTICE：此部分信息移动到数据库中保存，可在report对象中获取
  "auto_build": {
    // 生成节点
    "node": null,
    // 生成时间，CRON表达式
    "time": null,//"30 10 * * * ?",
    // 生成目录
    "dir": null, // "reports",
    // 是否按日期生成子目录
    "auto_build_use_date_subdir": false,
  },

  // 日统计开始时间偏移(分钟)
  "begin_delta": 0,
  // 日统计结束时间偏移(分钟)
  "end_delta": 0,
}

// https://dream-num.github.io/LuckysheetDocs/zh/guide/sheet.html#%E5%88%9D%E5%A7%8B%E5%8C%96%E9%85%8D%E7%BD%AE
const defaultSheet = {
  "name": "Sheet1",
  "color": "",
  "index": 0,
  "status": 1,
  "order": 0,
  "celldata": [],
  "config": {}
};

const defaultFileContent = (report) => {
  const content = {
    data: [defaultSheet],
    config: {
      ...defaultConfig, "book_type": ReportType.getReportTypeValue(report.report_type)
    },
  };
  return JSON.stringify(content);
}

export const ReportFile = {

  defaultFileContent,

  getFilePath(report, rootPath) {
    const path = rootPath;
    return `${path}${report.id}${REPORT_TPL_SUFFIX}`
  },

  async readContent(report) {
    const channel = await SparkChannel();
    const root_path = path.join(channel.context.path, 'reports');
    const file_path = ReportFile.getFilePath(report, root_path);
    const resp = await channel.request_open_file({ file_path });
    // console.log('open lxls data', resp.data);
    const file_content = resp.data && resp.data.file_content;
    const content = file_content || defaultFileContent(report);
    return JSON.parse(content);
  },

  async writeContent(report, file_content) {
    const report_id = report.id;
    const channel = await SparkChannel();
    const root_path = path.join(channel.context.path, 'reports');
    const resp = await channel.request_save_file({ report_id, file_path : root_path, file_content });
    return resp;
  },
}

export const OPTION_LXLS_ENV = [
  { value: 'REPORT_DATE', label: '制表日期', },
  { value: 'REPORT_DATETIME', label: '制表日期时间', },
  { value: 'REPORT_USER', label: '制表用户', },
];

// 测量点表类型
const TABLE_TYPES = [
  { value: 'ANALOG', label: '模拟量', id: 8 }, // 遥测
  { value: 'SIGNAL', label: '数字量', id: 9 }, // 遥信 只有实时数据才可选
  { value: 'DEGREE', label: '累积量', id: 10 }, // 电度
];
const TABLE_TYPE_MAP = {};
for (const tt of TABLE_TYPES) {
  TABLE_TYPE_MAP[tt.value] = tt.id;
}

export const TableType = {
  optionsForSeq() {
    return TABLE_TYPES.filter(v => v.value !== 'SIGNAL');
  },
  optionsForReal() {
    return TABLE_TYPES;
  },
  getTableTypeId: (value) => TABLE_TYPE_MAP[value],

}

// 填充数据类型
function dataType(key, value, label, desc, hasTime = false, colTitle = undefined) {
  return { key, value, label, desc, hasTime, colTitle };
}
const DATA_TYPES_MAP = {};

const DATA_TYPES = [
  dataType(0, "PERIOD", "周期", "PERIOD"),
  dataType(1, "MUTATION", "突变", "MUTATION"),
  dataType(2, "DIFF", "差值", "DIFF"),
  dataType(43, "HOUR_DIFF", "时差值", "DIFF"),
  dataType(50, "DAY_MEAN", "日平均值", "STATISTIC"),
  dataType(51, "DAY_MAX", "日最大值", "STATISTIC", true),
  dataType(52, "DAY_MIN", "日最小值", "STATISTIC", true),
  dataType(53, "DAY_DIFF", "日差值", "DIFF"),
  dataType(59, "DAY_LAST", "日末值", "LAST"),
  dataType(60, "WEEK_MEAN", "周平均值", "STATISTIC"),
  dataType(61, "WEEK_MAX", "周最大值", "STATISTIC", true),
  dataType(62, "WEEK_MIN", "周最小值", "STATISTIC", true),
  dataType(63, "WEEK_DIFF", "周差值", "DIFF"),
  dataType(69, "WEEK_LAST", "周末值", "LAST"),
  dataType(70, "MONTH_MEAN", "月平均值", "STATISTIC"),
  dataType(71, "MONTH_MAX", "月最大值", "STATISTIC", true),
  dataType(72, "MONTH_MIN", "月最小值", "STATISTIC", true),
  dataType(73, "MONTH_DIFF", "月差值", "DIFF"),
  dataType(79, "MONTH_LAST", "月末值", "LAST"),
  dataType(80, "YEAR_MEAN", "年平均值", "STATISTIC"),
  dataType(81, "YEAR_MAX", "年最大值", "STATISTIC", true),
  dataType(82, "YEAR_MIN", "年最小值", "STATISTIC", true),
  dataType(83, "YEAR_DIFF", "年差值", "DIFF"),
  dataType(89, "YEAR_LAST", "年末值", "LAST"),
];
for (const dt of DATA_TYPES) {
  DATA_TYPES_MAP[dt.value] = dt;
}

const STAT_TYPE_TREE = [
  {
    value: 'CATEGORY 1',
    title: '一般统计',
    selectable: false,
    children: [
      { value: 'MIN', title: '最小值/时间', hasTime: true },
      { value: 'MAX', title: '最大值/时间', hasTime: true },
      { value: 'AVG', title: '平均值', },
    ],
  },
  {
    value: 'CATEGORY 2',
    title: '绝对统计',
    selectable: false,
    children: [
      { value: 'ABS_MIN', title: '最小值/时间', hasTime: true },
      { value: 'ABS_MAX', title: '最大值/时间', hasTime: true },
      { value: 'ABS_AVG', title: '平均值', },
    ],
  },
  {
    value: 'CATEGORY 3',
    title: '计算统计',
    selectable: false,
    children: [
      { value: 'VOLT_ELIG', title: '电压合格率', },
      { value: 'OVER_TIME_HIGH', title: '越上限时间', colTitle: '越上限时间（秒）' },
      { value: 'OVER_TIME_LOW', title: '越下限时间', colTitle: '越下限时间（秒）' },
    ],
  },
];

for (const s of STAT_TYPE_TREE) {
  for (const c of s.children) {
    let label = c.title;
    if (c.hasTime) {
      label = label.replace('/时间', '');
    }
    const dt = dataType(-1, c.value, label, "STATISTIC", c.hasTime, c.colTitle)
    DATA_TYPES_MAP[dt.value] = dt;
  }
}

const filterDataTypes = (valuePatt, desc) => {
  return DATA_TYPES.filter(d => {
    if (valuePatt && !valuePatt.test(d.value)) {
      return false;
    }
    if (desc && desc !== d.desc) {
      return false;
    }
    return true;
  });
};

export const DataType = {
  optionsForSeq(bookType) {
    if (bookType === 'DAY') {
      return filterDataTypes(/^(PERIOD|HOUR_.*)$/);
    } else if (bookType === 'WEEK') {
      return filterDataTypes(/^DAY_/);
    } else if (bookType === 'MONTH') {
      return filterDataTypes(/^DAY_/);
    } else if (bookType === 'YEAR') {
      return filterDataTypes(/^MONTH_/);
    } else {
      return [];
    }
  },
  optionsForStat(bookType) {
    if (bookType === 'DAY') {
      return filterDataTypes(/^DAY_/, 'STATISTIC');
    } else if (bookType === 'WEEK') {
      return filterDataTypes(/^WEEK_/, 'STATISTIC');
    } else if (bookType === 'MONTH') {
      return filterDataTypes(/^MONTH_/, 'STATISTIC');
    } else if (bookType === 'YEAR') {
      return filterDataTypes(/^YEAR_/, 'STATISTIC');
    } else {
      return [];
    }
  },
  treeDataForStat(bookType) {
    return STAT_TYPE_TREE;
  },
  getByValue(value) {
    return DATA_TYPES_MAP[value];
  }
}

// curve page

export const PERIOD_OPTIONS = [{
  label: '单日',
  value: 'DATE',
}, {
  label: '多日',
  value: 'RANGE',
}, {
  label: '多日对照',
  value: 'COMPRANGE',
}];

export const MODE_OPTIONS = [{
  label: '通用曲线',
  value: 'GENERAL_CURVE',
}, {
  label: '秒级曲线',
  value: 'SECOND_CURVE',
}, {
  label: '小时棒图',
  value: 'HOUR_BAR',
}, {
  label: '日棒图',
  value: 'DAY_BAR',
}];

export const STEP_INTERVAL_OPTIONS = [{
  label: '秒',
  value: 'SEC_UNIT',
}, {
  label: '分',
  value: 'MIN_UNIT',
}];